package utils

import (
	"bytes"
	"context"
	"fmt"
	"github.com/skip2/go-qrcode"
	"image/color"
	"io"
	"os"
	"time"
)

type QR struct{}

var LocalQr *QR

func init() {
	LocalQr = &QR{}
}
func (q *QR) Generate(ctx context.Context, uid string, content string, size int, level qrcode.RecoveryLevel, foregroundColor color.Color, backgroundColor color.Color, disableBorder bool) (url string, err error) {
	if LocalQr != nil {
		qr, err := qrcode.New(content, level)
		if err != nil {
			return "", err
		}
		qr.ForegroundColor = foregroundColor
		qr.BackgroundColor = backgroundColor
		qr.DisableBorder = disableBorder
		png, err := qr.PNG(size)
		if err != nil {
			return "", err
		}
		dir := os.TempDir()
		filename := fmt.Sprintf("%d-%s%s", time.Now().Unix(), uid, ".png")
		tempFile, err := os.CreateTemp(dir, filename)
		if err != nil {
			return "", err
		}
		reader := bytes.NewReader(png)
		io.Copy(tempFile, reader)
		defer func(tempFile *os.File) {
			err := tempFile.Close()
			if err != nil {
				panic(err)
			}
		}(tempFile)
		local, err := LocalUploadUtils.UploadLocal(ctx, filename, tempFile.Name())
		if err != nil {
			return "", err
		}
		return local, nil

	} else {
		return "", err
	}
}
